package com.platform.usercenter.service.impl;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;

import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.platform.common.core.domain.base.BaseRequest;
import com.platform.common.core.domain.entity.SysDept;
import com.platform.common.core.exception.ServiceException;
import com.platform.common.core.utils.DateUtils;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.security.utils.SecurityUtils;
import com.platform.constants.SysUserConstants;
import com.platform.usercenter.domain.*;
import com.platform.usercenter.domain.dto.SelectOptionDTO;
import com.platform.usercenter.domain.dto.SysOrganizationDTO;
import com.platform.usercenter.domain.dto.SysOrganizationPermissionDTO;
import com.platform.usercenter.domain.request.SysOrganizationPermissionRequest;
import com.platform.usercenter.domain.vo.SysOrganizationInfo;
import com.platform.usercenter.domain.vo.SysOrganizationPermissionQuery;
import com.platform.usercenter.domain.vo.SysOrganizationVO;
import com.platform.usercenter.mapper.*;
import com.platform.usercenter.service.ISysUserCommonService;
import com.platform.usercenter.utils.TreeAdapterUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.platform.usercenter.service.ISysOrganizationService;

import javax.annotation.Resource;

/**
 * 组织Service业务层处理
 *
 * @author platform
 * @date 2024-10-24
 */
@Service
public class SysOrganizationServiceImpl implements ISysOrganizationService {
    @Resource
    private SysOrganizationMapper sysOrganizationMapper;
    @Resource
    private SysOrganizationRelationMapper sysOrganizationRelationMapper;
    @Resource
    private SysAppPermissionMapper sysAppPermissionMapper;

    @Resource
    private SysOrganizationPermissionMapper sysOrganizationPermissionMapper;

    @Resource
    private ISysUserCommonService userCommonService;

    /**
     * 查询组织
     *
     * @param orgId 组织主键
     * @return 组织
     */
    @Override
    public SysOrganization selectSysOrganizationByOrgId(Long orgId) {
        return sysOrganizationMapper.selectSysOrganizationByOrgId(orgId);
    }

    @Override
    public SysOrganizationInfo selectSysOrganizationInfo(Long orgId) {
        SysOrganizationInfo info = new SysOrganizationInfo();
        //查询组织信息
        SysOrganization sysOrganization = sysOrganizationMapper.selectSysOrganizationByOrgId(orgId);
        if (ObjectUtil.isEmpty(sysOrganization)) {
            return info;
        }
        BeanUtils.copyProperties(sysOrganization, info);
        // 查询下游组织信息-实际关系
        SysOrganizationRelation relationQuery = new SysOrganizationRelation();
        relationQuery.setOrgId(orgId);
        relationQuery.setRelation(SysUserConstants.ORG_REAL);
        relationQuery.setIsDelete(SysUserConstants.N);
        List<SysOrganizationRelation> realOrgList = sysOrganizationRelationMapper.selectSysOrganizationRelationList(relationQuery);
        if (CollectionUtil.isNotEmpty(realOrgList)) {
            SysOrganizationRelation realOrgInfo = realOrgList.get(0);
            info.setParentId(realOrgInfo.getParentId());
        }
        // 查询下游组织信息-业务下游
        SysOrganizationRelation relation = new SysOrganizationRelation();
        relation.setParentId(orgId);
        relation.setRelation(SysUserConstants.ORG_BUSINESS);
        relation.setIsDelete(SysUserConstants.N);
        List<SysOrganizationRelation> relationList = sysOrganizationRelationMapper.selectSysOrganizationRelationList(relation);
        if (CollectionUtil.isNotEmpty(relationList)) {
            Set<Long> appSceneIds = relationList.stream().map(SysOrganizationRelation::getOrgId).collect(Collectors.toSet());
            info.setUpAndDownOrgIds(appSceneIds);
        }
        // 查询组织应用关联信息
        SysOrganizationPermissionQuery permission = new SysOrganizationPermissionQuery();
        permission.setOrgId(orgId);
        permission.setIsDelete(SysUserConstants.N);
        List<SysOrganizationPermissionDTO> permissionList = sysOrganizationPermissionMapper.selectSysOrganizationPermissionDTOList(permission);
        if (CollectionUtil.isNotEmpty(permissionList)) {
            for (SysOrganizationPermissionDTO dto : permissionList) {
                if (StringUtils.isNotEmpty(dto.getValue())) {
                    List<SelectOptionDTO> selectOptionDTOS = JSON.parseArray(dto.getValue(), SelectOptionDTO.class);
                    dto.setSelectOptionDTOS(selectOptionDTOS);
                    dto.setOptionValues(selectOptionDTOS.stream().map(SelectOptionDTO::getValue).distinct().collect(Collectors.toList()));
                }
            }
            info.setPermissionList(permissionList);
            // 应用id去重
            Set<Long> appSceneIds = permissionList.stream().map(SysOrganizationPermissionDTO::getAppSceneId).collect(Collectors.toSet());
            // 根据应用id分组
            Map<Long, List<SysOrganizationPermissionDTO>> permissionMap = permissionList.stream().collect(Collectors.groupingBy(item -> item.getAppSceneId()));
            if (ObjectUtil.isNotEmpty(permissionMap)) {
                info.setAppMap(permissionMap);
            }
            info.setAppSceneIds(appSceneIds);
        }
        return info;

    }


    /**
     *
     * 获取当前登录用户登录组织的上下游组织关系
     * @param orgId
     * @return
     */
    @Override
    public List<SysOrganizationRelation> selectUpAndDownOrgs(Long orgId) {
        // 查询下游组织信息-业务下游
        SysOrganizationRelation relation = new SysOrganizationRelation();
        relation.setParentId(orgId);
        relation.setRelation(SysUserConstants.ORG_BUSINESS);
        relation.setIsDelete(SysUserConstants.N);
        List<SysOrganizationRelation> relationList = sysOrganizationRelationMapper.selectSysOrganizationRelationList(relation);
        return relationList;

    }

    @Override
    public List<SysOrganizationRelation> selectUpAndDownOrgsByParentOrgIds(Set<Long> orgIds) {
        // 查询下游组织信息-业务下游
        SysOrganizationRelation relation = new SysOrganizationRelation();
        relation.setParentIds(orgIds);
        relation.setRelation(SysUserConstants.ORG_BUSINESS);
        relation.setIsDelete(SysUserConstants.N);
        List<SysOrganizationRelation> relationList = sysOrganizationRelationMapper.selectSysOrganizationRelationList(relation);
        return relationList;

    }

    /**
     * 查询组织列表
     *
     * @param sysOrganization 组织
     * @return 组织
     */
    @Override
    public List<SysOrganization> selectSysOrganizationList(SysOrganization sysOrganization) {
        sysOrganization.setIsDelete(SysUserConstants.N);
        return sysOrganizationMapper.selectSysOrganizationList(sysOrganization);
    }

    @Override
    public List<SysOrganizationVO> listTree(SysOrganization sysOrganization) {
        List<SysOrganizationVO> organizations = sysOrganizationMapper.listTree(sysOrganization);
        if (CollectionUtil.isNotEmpty(organizations)) {
            return TreeAdapterUtil.buildTree(organizations, SysOrganizationVO.class, null);
        } else {
            return null;
        }
    }
    @Override
    public List<SysOrganizationVO> listOrgTree(SysOrganization sysOrganization) {
        List<SysOrganizationVO> organizations = sysOrganizationMapper.listTree(sysOrganization);
        return organizations;
    }

    @Override
    public SysOrganizationVO listTreeByUserOrg(SysOrganization sysOrganization, Long orgId) {
        List<SysOrganizationVO> organizations = sysOrganizationMapper.listTree(sysOrganization);
        return findOrgAndBuildChildren(organizations, orgId);
    }

    public static SysOrganizationVO findOrgAndBuildChildren(List<SysOrganizationVO> allOrgs, Long targetOrgId) {
        // 1. 检查输入合法性
        if (allOrgs == null || allOrgs.isEmpty()) {
            return null;
        }
        // 2. 构建父节点到子节点的映射（parentId -> List<子节点>）
        Map<Long, List<SysOrganizationVO>> parentToChildrenMap = allOrgs.stream()
                .collect(Collectors.groupingBy(SysOrganizationVO::getParentId));
        // 3. 查找目标组织
        SysOrganizationVO targetOrg = allOrgs.stream()
                .filter(org -> Objects.equals(org.getOrgId(), targetOrgId))
                .findFirst()
                .orElse(null);
        if (targetOrg == null) {
            return null;
        }
        // 4. 递归构建目标组织的子树
        buildChildrenHierarchy(targetOrg, parentToChildrenMap);
        return targetOrg; // 返回包含完整子树的目标组织
    }

    private static void buildChildrenHierarchy(SysOrganizationVO parent,
                                               Map<Long, List<SysOrganizationVO>> parentToChildrenMap) {
        // 获取当前父节点的直接子节点（parentId = 父节点的 orgId）
        List<SysOrganizationVO> children = parentToChildrenMap.getOrDefault(parent.getOrgId(), new ArrayList<>());
        // 递归处理每个子节点，构建其子树
        for (SysOrganizationVO child : children) {
            buildChildrenHierarchy(child, parentToChildrenMap); // 先构建子节点的子树
        }
        // 将子节点列表设置到父节点的 children 属性中（覆盖原有数据，若有的话）
        parent.setChildren(children);
    }

    @Override
    public List<SysOrganizationVO> listTreeByUserId(Long userId) {
        List<SysOrganizationVO> organizations;
        if (userCommonService.isAdmin(userId)) {
            organizations = sysOrganizationMapper.listTree(new SysOrganization());
        } else {
            organizations = sysOrganizationMapper.listTreeByUserId(userId);
        }
        if (CollectionUtil.isNotEmpty(organizations)) {
            return TreeAdapterUtil.buildTreeWithoutRootAppendList(organizations, SysOrganizationVO.class, null);
        } else {
            return null;
        }
    }

    public static List<SysOrganizationVO> buildTree(List<SysOrganizationVO> organizations) {
        List<SysOrganizationVO> tree = new ArrayList<>();
        for (SysOrganizationVO scene : organizations) {
            if (scene.getParentId() == 0) {
                tree.add(buildSubTree(scene, organizations));
            }
        }
        return tree;
    }

    private static SysOrganizationVO buildSubTree(SysOrganizationVO root, List<SysOrganizationVO> organizations) {
        for (SysOrganizationVO scene : organizations) {
            if (Objects.equals(scene.getParentId(), root.getOrgId())) {
                root.getChildren().add(buildSubTree(scene, organizations));
            }
        }
        return root;
    }

    /**
     * 新增组织
     *
     * @param sysOrganization 组织
     * @return 结果
     */
    @Override
    public int insertSysOrganization(SysOrganization sysOrganization) {
        sysOrganization.setCreateTime(DateUtils.getNowDate());
        return sysOrganizationMapper.insertSysOrganization(sysOrganization);
    }

    @Override
    public int insertSysOrganizationInfo(SysOrganizationDTO dto) {
        //新增组织信息--校验真实上级是否已经存在
        SysOrganization organizationQuery = new SysOrganization();
        organizationQuery.setOrgName(dto.getOrgName());
        organizationQuery.setIsDelete(SysUserConstants.N);
        List<SysOrganization> organizations = sysOrganizationMapper.selectSysOrganizationListCheck(organizationQuery);
        if (CollectionUtil.isNotEmpty(organizations)) {
            throw new ServiceException(dto.getOrgName() + "-该组织信息已存在！");
        }
        dto.setCreateBy(SecurityUtils.getUsername());
        dto.setCreateTime(DateUtils.getNowDate());
        dto.setIsDelete(SysUserConstants.N);
        int rows = sysOrganizationMapper.insertSysOrganization(dto);
        if (rows > 0) {
            if (ObjectUtil.isNotEmpty(dto.getParentId())) {
                SysOrganizationRelation relation = new SysOrganizationRelation();
                relation.setParentId(dto.getParentId());
                relation.setOrgId(dto.getOrgId());
                relation.setRelation(SysUserConstants.ORG_REAL);
                relation.setCreateBy(SecurityUtils.getUsername());
                relation.setCreateTime(DateUtils.getNowDate());
                relation.setIsDelete(SysUserConstants.N);
                sysOrganizationRelationMapper.insertSysOrganizationRelation(relation);
            }

            //新增下游组织关联关系--业务组织校验
            if (CollectionUtil.isNotEmpty(dto.getUpAndDownOrgIds())) {
                for (Long orgid : dto.getUpAndDownOrgIds()) {
                    SysOrganizationRelation upAndDownOrg = new SysOrganizationRelation();
                    upAndDownOrg.setOrgId(orgid);
                    upAndDownOrg.setParentId(dto.getOrgId());
                    upAndDownOrg.setRelation(SysUserConstants.ORG_BUSINESS);
                    upAndDownOrg.setCreateBy(SecurityUtils.getUsername());
                    upAndDownOrg.setCreateTime(DateUtils.getNowDate());
                    upAndDownOrg.setIsDelete(SysUserConstants.N);
                    sysOrganizationRelationMapper.insertSysOrganizationRelation(upAndDownOrg);
                }
            }
            //新增应用场景关联关系
            if (CollectionUtil.isNotEmpty(dto.getPermissionList())) {
                for (SysOrganizationPermissionRequest permissionRequest : dto.getPermissionList()) {
                    // 新增组织应用权限关联数据
                    SysOrganizationPermission appPermission = new SysOrganizationPermission();
                    appPermission.setPermissionId(permissionRequest.getPermissionId());
                    appPermission.setOrgId(dto.getOrgId());
                    appPermission.setAppSceneId(permissionRequest.getAppSceneId());
                    appPermission.setName(Optional.ofNullable(permissionRequest.getName()).orElse(null));
                    appPermission.setCode(Optional.ofNullable(permissionRequest.getCode()).orElse(null));
                    if (StringUtils.isNotEmpty(permissionRequest.getSelectOptionDTOS())) {
                        appPermission.setValue(JSON.toJSONString(permissionRequest.getSelectOptionDTOS()));
                    }
                    appPermission.setCreateBy(SecurityUtils.getUsername());
                    appPermission.setCreateTime(DateUtils.getNowDate());
                    appPermission.setIsDelete(SysUserConstants.N);
                    sysOrganizationPermissionMapper.insertSysOrganizationPermission(appPermission);
                }
            }
        }
        return rows;
    }

    /**
     * 修改组织
     *
     * @param sysOrganization 组织
     * @return 结果
     */
    @Override
    public int updateSysOrganization(SysOrganization sysOrganization) {
        sysOrganization.setUpdateTime(DateUtils.getNowDate());
        return sysOrganizationMapper.updateSysOrganization(sysOrganization);
    }

    /**
     * 修改组织
     *
     * @param dto 组织
     * @return 结果
     */
    @Override
    public int updateSysOrganizationInfo(SysOrganizationDTO dto) {
        //新增组织信息--校验真实上级是否已经存在
        SysOrganization organizationQuery = new SysOrganization();
        organizationQuery.setOrgName(dto.getOrgName());
        organizationQuery.setIsDelete(SysUserConstants.N);
        List<SysOrganization> organizations = sysOrganizationMapper.selectSysOrganizationListCheck(organizationQuery);
        if (CollectionUtil.isNotEmpty(organizations) && !organizations.get(0).getOrgId().equals(dto.getOrgId())) {
            throw new ServiceException(dto.getOrgName() + "-该组织信息已存在！");
        }
        dto.setUpdateBy(SecurityUtils.getUsername());
        dto.setUpdateTime(DateUtils.getNowDate());
        dto.setIsDelete(SysUserConstants.N);
        int rows = sysOrganizationMapper.updateSysOrganization(dto);
        if (rows > 0) {

            // 先删除之前的关联关系，再新增修改后的关联关系
            SysOrganizationRelation delRelation = new SysOrganizationRelation();
            delRelation.setOrgId(dto.getOrgId());
            delRelation.setIsDelete(SysUserConstants.Y);
            delRelation.setDeleteBy(SecurityUtils.getUsername());
            delRelation.setDeleteTime(DateUtils.getNowDate());
            sysOrganizationRelationMapper.updateSysOrganizationRelationByOrgId(delRelation);
            // 删除父节点为当前组织的关联关系
            SysOrganizationRelation delParentRelation = new SysOrganizationRelation();
            delParentRelation.setParentId(dto.getOrgId());
            delParentRelation.setIsDelete(SysUserConstants.Y);
            delParentRelation.setDeleteBy(SecurityUtils.getUsername());
            delParentRelation.setDeleteTime(DateUtils.getNowDate());
            sysOrganizationRelationMapper.updateSysOrganizationRelationByParentId(delParentRelation);
            if (ObjectUtil.isNotEmpty(dto.getParentId())) {
                SysOrganizationRelation relation = new SysOrganizationRelation();
                relation.setParentId(dto.getParentId());
                relation.setOrgId(dto.getOrgId());
                relation.setRelation(SysUserConstants.ORG_REAL);
                relation.setCreateBy(SecurityUtils.getUsername());
                relation.setCreateTime(DateUtils.getNowDate());
                relation.setIsDelete(SysUserConstants.N);
                sysOrganizationRelationMapper.insertSysOrganizationRelation(relation);
            }
            //新增下游组织关联关系--业务组织校验
            if (CollectionUtil.isNotEmpty(dto.getUpAndDownOrgIds())) {
                for (Long orgid : dto.getUpAndDownOrgIds()) {
                    SysOrganizationRelation upAndDownOrg = new SysOrganizationRelation();
                    upAndDownOrg.setOrgId(orgid);
                    upAndDownOrg.setParentId(dto.getOrgId());
                    upAndDownOrg.setRelation(SysUserConstants.ORG_BUSINESS);
                    upAndDownOrg.setCreateBy(SecurityUtils.getUsername());
                    upAndDownOrg.setCreateTime(DateUtils.getNowDate());
                    upAndDownOrg.setIsDelete(SysUserConstants.N);
                    sysOrganizationRelationMapper.insertSysOrganizationRelation(upAndDownOrg);
                }
            }
            //新增应用场景关联关系
            if (CollectionUtil.isNotEmpty(dto.getPermissionList())) {
                // 删除该组织的全部应用场景
                SysOrganizationPermission delPermission = new SysOrganizationPermission();
                delPermission.setOrgId(dto.getOrgId());
                delPermission.setIsDelete(SysUserConstants.Y);
                delPermission.setDeleteBy(SecurityUtils.getUsername());
                delPermission.setDeleteTime(DateUtils.getNowDate());
                sysOrganizationPermissionMapper.updateSysOrganizationPermissionByOrgId(delPermission);
                for (SysOrganizationPermissionRequest permissionRequest : dto.getPermissionList()) {
                    // 新增组织应用权限关联数据
                    SysOrganizationPermission appPermission = new SysOrganizationPermission();
                    appPermission.setPermissionId(permissionRequest.getPermissionId());
                    appPermission.setOrgId(dto.getOrgId());
                    appPermission.setAppSceneId(permissionRequest.getAppSceneId());
                    appPermission.setName(Optional.ofNullable(permissionRequest.getName()).orElse(null));
                    appPermission.setCode(Optional.ofNullable(permissionRequest.getCode()).orElse(null));
                    if (StringUtils.isNotEmpty(permissionRequest.getSelectOptionDTOS())) {
                        appPermission.setValue(JSON.toJSONString(permissionRequest.getSelectOptionDTOS()));
                    }
                    appPermission.setCreateBy(SecurityUtils.getUsername());
                    appPermission.setCreateTime(DateUtils.getNowDate());
                    appPermission.setIsDelete(SysUserConstants.N);
                    sysOrganizationPermissionMapper.insertSysOrganizationPermission(appPermission);
                }
            }
        }
        return rows;


    }

    /**
     * 批量删除组织
     *
     * @param orgIds 需要删除的组织主键
     * @return 结果
     */
    @Override
    public int deleteSysOrganizationByOrgIds(Long[] orgIds) {
        return sysOrganizationMapper.deleteSysOrganizationByOrgIds(orgIds);
    }

    /**
     * 删除组织信息
     *
     * @param orgId 组织主键
     * @return 结果
     */
    @Override
    public int deleteSysOrganizationByOrgId(Long orgId) {
        return sysOrganizationMapper.deleteSysOrganizationByOrgId(orgId);
    }

    @Override
    public List<SysOrganizationVO> selectSysOrganizationTree() {
        List<SysOrganizationVO> organizationVOList = new ArrayList<>();
        // 查询具有真实关系的组织
        List<SysOrganizationVO> organizationVOS = sysOrganizationMapper.selectSysOrganizationTree(new SysOrganization());
        if (CollectionUtil.isNotEmpty(organizationVOS)) {
            // 处理组织树
            organizationVOList = buildOrganizationTree(organizationVOS);
        }
        return organizationVOList;
    }

    @Override
    public List<SysOrganizationVO> userAllOrgTree() {
        List<SysOrganizationVO> organizationVOList = new ArrayList<>();
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        // 查询具有真实关系的组织
        List<SysOrganizationVO> organizationVOS = sysOrganizationMapper.userAllOrgTree(userId);
//        if(CollectionUtil.isNotEmpty(organizationVOS)){
//            // 处理组织树
//            organizationVOList= TreeAdapterUtil.buildTree(organizationVOS,SysOrganizationVO.class);
//        }
        return organizationVOS;
    }

    @Override
    public List<SysOrganization> selectSysOrganizationListByUserId(Long userId) {
        return sysOrganizationMapper.selectSysOrganizationListByUserId(userId);
    }

    @Override
    public HashSet< String > getAirportListByOrgAndUser( BaseRequest res ) throws JsonProcessingException {
        List< String > airportListByOrgAndUser=sysOrganizationMapper.getAirportListByOrgAndUser( res );
        HashSet<String> list = new HashSet<>();
        for(String json: airportListByOrgAndUser) {
            if(StringUtils.isNotEmpty( json )){
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonNode = objectMapper.readTree(json);
                for (JsonNode node : jsonNode) {
                    list.add(node.get("value").asText());
                }
            }
        }
        return list;
    }

    public List<SysOrganizationVO> buildOrganizationTree(List<SysOrganizationVO> organizationVOS) {
        List<SysOrganizationVO> returnList = new ArrayList<>();
        // 过滤顶级节点
        List<Long> tempList = organizationVOS.stream().map(SysOrganizationVO::getOrgId).collect(Collectors.toList());
        for (SysOrganizationVO vo : organizationVOS) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(vo.getParentId())) {
                recursionFn(organizationVOS, vo);
                returnList.add(vo);
            }
        }
        if (returnList.isEmpty()) {
            returnList = organizationVOS;
        }
        return returnList;
    }

    /**
     * 递归处理组织树
     */
    public List<SysOrganizationVO> dealOrganizationTree(List<SysOrganizationVO> organizationVOS) {
        List<SysOrganizationVO> organizationVOList = new ArrayList<>();
        //按照父id进行分组
//        organizationVOS.stream()
        Map<Long, List<SysOrganizationVO>> nodeMap = organizationVOS.stream().collect(Collectors.groupingBy(SysOrganizationVO::getParentId));
        for (SysOrganizationVO vo : organizationVOS) {
            SysOrganizationVO organizationVO = new SysOrganizationVO();
            organizationVO.setOrgId(vo.getOrgId());
            organizationVO.setOrgName(vo.getOrgName());
            if (ObjectUtil.isNotEmpty(vo.getParentId())) {
                organizationVO.setChildren(nodeMap.get(vo.getParentId()));
            }
            organizationVOList.add(organizationVO);
        }
        return organizationVOList;
    }


    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysOrganizationVO> getChildPerms(List<SysOrganizationVO> list, Long parentId) {
        List<SysOrganizationVO> returnList = new ArrayList<SysOrganizationVO>();
        for (Iterator<SysOrganizationVO> iterator = list.iterator(); iterator.hasNext(); ) {
            SysOrganizationVO t = (SysOrganizationVO) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }


    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SysOrganizationVO> list, SysOrganizationVO t) {
        // 得到子节点列表
        List<SysOrganizationVO> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysOrganizationVO tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }


    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysOrganizationVO> list, SysOrganizationVO t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 得到子节点列表
     */
    private List<SysOrganizationVO> getChildList(List<SysOrganizationVO> list, SysOrganizationVO t) {
        List<SysOrganizationVO> tlist = new ArrayList<SysOrganizationVO>();
        Iterator<SysOrganizationVO> it = list.iterator();
        while (it.hasNext()) {
            SysOrganizationVO n = (SysOrganizationVO) it.next();
            if (ObjectUtil.isNotEmpty(n.getParentId())) {
                if (n.getParentId().longValue() == t.getOrgId().longValue()) {
                    tlist.add(n);
                }
            }

        }
        return tlist;
    }
}
